package com.huangtang.pc.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ThreadLocal工具类
 * @author sunjf
 * @date 2024/01/11
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class ThreadLocalUtil{

    private static final ThreadLocal<Map<Object,Object>> threadLocal = ThreadLocal.withInitial(HashMap::new);

    private static Map<Object,Object> getAllData(){
        return threadLocal.get();
    }

    private static void setAllData(Map<Object,Object> data){
        threadLocal.set(data);
    }

    private static <T> T get(String key, T defaultValue){
        try{
            return (T) getAllData().getOrDefault(key,defaultValue);
        }catch (Throwable e){
            log.error("ThreadLocalUtil get error",e);
            throw new RuntimeException("ThreadLocalUtil get error",e);
        }
    }

    /**
     * 根据key获取当前线程局部变量信息
     * @param key key
     * @return T
     * @param <T> T
     */
    public static <T> T get(String key){
        try{
            return get(key,null);
        }catch (Exception e){
            log.error("ThreadLocalUtil get error",e);
            throw new RuntimeException("ThreadLocalUtil get error",e);
        }
    }

    /**
     * 设置当前线程局部变量信息
     * @param key key
     * @param value value
     * @return T
     * @param <T> T
     */
    public static <T> T set(String key, T value) {
        try{
            getAllData().put(key,value);
            return value;
        }catch (Throwable e){
            log.error("set value error",e);
            throw new RuntimeException("set value error",e);
        }
    }

    /**
     * 移除当前线程局部变量信息
     * @param key key
     */
    public static void remove(String key){
        getAllData().remove(key);
    }

    public static void clearAll(){
        threadLocal.remove();
    }

}
